﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;

namespace jqwidgetsapi.Models
{
    public class CsvRepository
    {
        private string series_real_path;
        private List<CsvFile> l_files = new List<CsvFile>();

        public CsvRepository()
        {
            series_real_path = HttpContext.Current.Server.MapPath("~/App_Data/Series/");
            var files = Directory.EnumerateFiles(series_real_path);
            foreach (string f in files)
            {
                l_files.Add(new CsvFile(f));
            }
        }

        public static string isIdOk(string name)
        {
            StringBuilder msg = new StringBuilder();

            var a_n = name.Split('_');
            try
            {
                if (!(a_n[1].ToString().Contains(".csv")))
                    msg.Append("<p>File extension must be .csv</p>");
                var lista = new CsvRepository().returnSingleSeries(Convert.ToInt16(a_n[0]));
                if (lista != null)
                    msg.Append("<p>Sorry but an Id ").Append(a_n[0]).Append(" series already exists</p>");
            }
            catch (Exception)
            {
                msg.Append("<p>The file name is not the standard id_name.csv file</p>");
            }

            return msg.ToString();
        }

        public List<Series> returnAll()
        {
            List<Series> ls = new List<Series>();
            Series series = null;

            foreach (CsvFile c in l_files)
            {
                var name = c.Name;
                var id = c.Id;
                var file_path = series_real_path + id.ToString() + "_" + name + ".csv";
                var csv = HttpContext.Current.Server.HtmlEncode(File.ReadAllText(file_path, System.Text.Encoding.GetEncoding("iso-8859-3")));
                var a_csv = csv.Split('\r');

                series = new Series();
                series.Id = id;
                series.Name = name;

                for (int i = 1; i < a_csv.Length; i++)
                {
                    var a_line = a_csv[i].Replace("\n", string.Empty).Split(';');
                    if (a_line.Length > 1)
                    {
                        var p = new DataPoint();
                        p.Id = i;
                        p.X = Convert.ToDecimal(a_line[0]);
                        if (a_line[1] == string.Empty)
                            p.Y = null;
                        else
                            p.Y = Convert.ToDecimal(a_line[1]);
                        p.XLabel = a_line[2];
                        p.YLabel = a_line[3];
                        p.Notes = a_line[4];
                        series.add(p);
                    }
                }
                ls.Add(series);
            }
            return ls;
        }

        public Series returnSingleSeries(short id)
        {
            Series series = null;
            var fv = from p in l_files where p.Id == id select p;
            if (fv.Count() > 0)
            {
                var name = fv.First().Name;
                var file_path = series_real_path + id.ToString() + "_" + name + ".csv";
                var csv = HttpContext.Current.Server.HtmlEncode(File.ReadAllText(file_path, System.Text.Encoding.GetEncoding("iso-8859-3")));
                var a_csv = csv.Split('\r');

                series = new Series();
                series.Id = id;
                series.Name = name;

                for (int i = 1; i < a_csv.Length; i++)
                {
                    var a_line = a_csv[i].Replace("\n", string.Empty).Split(';');
                    if (a_line.Length > 1)
                    {
                        var p = new DataPoint();
                        p.X = Convert.ToDecimal(a_line[0]);
                        if (a_line[1] == string.Empty)
                            p.Y = null;
                        else
                            p.Y = Convert.ToDecimal(a_line[1]);
                        p.XLabel = a_line[2];
                        p.YLabel = a_line[3];
                        p.Notes = a_line[4];
                        series.add(p);
                    }
                }
                return series;
            }
            else
                return null;

        }
    }

    public class CsvFile
    {
        public CsvFile(string file_name)
        {
            file_name = file_name.Substring(file_name.LastIndexOf("\\")).Replace(".csv", string.Empty).Replace("\\", string.Empty);
            var fn = file_name.Split('_');
            if (fn.Length == 2)
            {
                _id = Convert.ToInt16(fn[0]);
                _name = fn[1];
            }
            else
            {
                throw new Exception("File Name non valid");
            }
        }

        private short _id;
        private string _name;
        public short Id { get { return _id; } }
        public string Name { get { return _name; } }
    }
}